package com.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.book.dao.BookClassDao;
import com.book.dto.ClassPage;
import com.book.entity.BookClass;
import com.book.service.BookClassService;
import com.book.utils.ResponseResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

//错误码12001开始
@Service
public class BookClassServiceImpl implements BookClassService {
    @Autowired
    private BookClassDao bookClassDao;

    @Override
    public ResponseResult getClass(ClassPage classPage) {
        try {
            QueryWrapper<BookClass> qw = new QueryWrapper<>();
            qw.like("class_name",classPage.getClassName());
            qw.orderByDesc("id");
            PageHelper.startPage(classPage.getCurrentPage(),classPage.getPageSize());
            List<BookClass> bookClassList = bookClassDao.selectList(qw);
            PageInfo<BookClass> classPageInfo = new PageInfo<>(bookClassList);
            if(classPage.getCurrentPage()>classPageInfo.getPages()){
                PageHelper.startPage(classPageInfo.getPages(),classPage.getPageSize());
                bookClassList = bookClassDao.selectList(qw);
                classPageInfo = new PageInfo<>(bookClassList);
            }
            return new ResponseResult(200,"查询分类成功",classPageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(12001,"查询分类失败");
        }
    }

    @Override
    public ResponseResult deleteClass(int id) {
        try {
            bookClassDao.deleteById(id);
            return new ResponseResult(200,"删除分类成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(12002,"删除分类失败");
        }
    }

    @Override
    public ResponseResult getOne(int id) {
        try {
            return new ResponseResult(200,"此分类信息获取成功",bookClassDao.selectById(id));
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(12003,"此分类信息获取失败");
        }
    }

    @Override
    public ResponseResult saveClass(BookClass bookClass) {
        try {
            if(bookClass.getId()==0){
                //说明是添加
                bookClassDao.insert(bookClass);
            }else {
                //说明是更新
                bookClassDao.updateById(bookClass);
            }
            return new ResponseResult(200,"保存分类信息成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(12004,"保存分类信息失败");
        }
    }
}
